package com.witdata.framework.service.docker.impl;

import com.alibaba.fastjson2.JSON;
import com.witdata.common.domain.docker.Container;
import com.witdata.common.domain.docker.Execute;
import com.witdata.common.domain.dto.ExecuteDto;
import com.witdata.common.domain.dto.InstanceContainerDto;
import com.witdata.framework.service.docker.ExecuteService;
import com.witdata.rabbit.domain.Handle;
import com.witdata.rabbit.producer.InstanceProducer;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ExecuteServiceImpl implements ExecuteService {
    private final InstanceProducer instanceProducer;

    @Override
    public String createExecute(InstanceContainerDto instanceContainerDto) {
        String data = instanceProducer.send(instanceContainerDto.getInstanceId(), Handle.CreateExecute, Container.builder()
                        .id(instanceContainerDto.getContainerId())
                .build());
        System.out.println("data = " + data);
        ExecuteDto executeDto = JSON.parseObject(data, ExecuteDto.class);
        return executeDto.getExecuteId();
    }

    @Override
    public void startExecute(ExecuteDto executeDto) {
        instanceProducer.send(executeDto.getInstanceId(), Handle.StartExecute, Execute.builder()
                        .id(executeDto.getExecuteId())
                .build());
    }

    @Override
    public void sendCommand(ExecuteDto executeDto) {
        instanceProducer.syncSend(executeDto.getInstanceId(), Handle.RunCommand, Execute.builder()
                        .id(executeDto.getExecuteId())
                        .command(executeDto.getCommand())
                .build());
    }

    @Override
    public void stopCommand(ExecuteDto executeDto) {
        instanceProducer.send(executeDto.getInstanceId(), Handle.StopExecute, Execute.builder()
                .id(executeDto.getExecuteId())
                .build()
        );
    }

    @Override
    public void removeExecute(ExecuteDto executeDto) {
        instanceProducer.send(executeDto.getInstanceId(), Handle.RemoveExecute, Execute.builder()
                .id(executeDto.getExecuteId())
                .build());
    }
}
